/**
 * Project Name:mauto-web
 * File Name:AreaService.java
 * Package Name:com.inftech.mauto.sys.service
 * Date:2016年10月7日下午9:14:13
 * Copyright (c) 2016, inf-technology Co., Ltd. All Rights Reserved.
 *
*/

package com.inftech.mauto.sys.service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.apache.shiro.session.InvalidSessionException;
import org.apache.shiro.session.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.inftech.mauto.common.constant.BusinessConstant;
import com.inftech.mauto.common.constant.SessionConstEnum;
import com.inftech.mauto.common.utils.CommonUtils;
import com.inftech.mauto.sys.dao.IEnterpriseDao;
import com.inftech.mauto.sys.entity.Enterprise;
import com.mingsoft.base.biz.impl.BaseBizImpl;
import com.mingsoft.base.dao.IBaseDao;
import com.mingsoft.people.dao.IPeopleDao;
import com.mingsoft.weixin.dao.IWeixinPeopleDao;
import com.mingsoft.weixin.entity.WeixinPeopleEntity;
import com.mingsoft.weixin.http.HttpClientConnectionManager;

import net.mingsoft.basic.security.session.CacheSessionDAO;

/**
 * ClassName:EnterpriseService <br/>
 * Function: 服务单位业务service. <br/>
 * Date: 2016年10月7日 下午9:14:13 <br/>
 * 
 * @author puyf
 * @version
 * @since JDK 1.7
 */
@SuppressWarnings({ "unchecked", "rawtypes" })
@Service("enterpriseService")
public class EnterpriseService extends BaseBizImpl {

	/**
	 * 服务单位持久化层注入
	 */
	@Autowired
	private IEnterpriseDao enterpriseDao;

	/**
	 * 用户持久化层注入
	 */
	@Autowired
	private IWeixinPeopleDao weixinPeopleDao;

	/**
	 * 用户持久化层
	 */
	@Autowired
	private IPeopleDao peopleDao;

	/**
	 * 会话dao
	 */
	@Autowired
	private CacheSessionDAO sessionDao;

	/**
	 * 后台服务器地址
	 */
	@Value("${adminUrl}")
	private String adminUrl;

	@Override
	protected IBaseDao getDao() {
		return enterpriseDao;
	}

	/**
	 * 
	 * queryEnterpriseListFront:前台查询服务单位列表. <br/>
	 *
	 * @author puyf
	 * @return
	 * @throws Exception
	 * @since JDK 1.7
	 */
	public List<Map<String, Object>> queryEnterpriseListFront() throws Exception {
		// 获取服务单位列表
		List<Enterprise> enterpriseList = enterpriseDao.queryEnterpriseList(new HashMap());
		// 返回列表
		List<Map<String, Object>> resultList = new ArrayList<Map<String, Object>>();
		if (enterpriseList != null && enterpriseList.size() != 0) {
			for (Enterprise enterprise : enterpriseList) {
				Map<String, Object> enterpriseM = new HashMap<String, Object>();
				// 企业id
				enterpriseM.put("id", enterprise.getId());
				// 企业名称
				enterpriseM.put("enterpriseName", enterprise.getEnterpriseName());
				// 企业地址
				enterpriseM.put("enterpriseAddress", enterprise.getEnterpriseAddress());
				// 企业服务电话
				enterpriseM.put("enterpriseTel", enterprise.getEnterpriseTel());
				resultList.add(enterpriseM);
			}
		}
		return resultList;
	}

	/**
	 * 
	 * queryNearestEnterpriseId:获取最近的服务单位id. <br/>
	 *
	 * @author puyf
	 * @param from
	 * @return
	 * @throws Exception
	 * @since JDK 1.7
	 */
	public Integer queryNearestEnterpriseId(String from) throws Exception {
		LOG.debug("from:" + from);
		Integer enterpriseId = null;
		// 纬度
		double lat1 = Double.valueOf(from.split(",")[0]);
		// 经度
		double lng1 = Double.valueOf(from.split(",")[1]);
		// 获取服务单位列表
		List<Enterprise> enterpriseList = enterpriseDao.queryEnterpriseList(new HashMap());
		BigDecimal distance = null;
		Integer position = null;
		int i = 0;
		if (enterpriseList != null && enterpriseList.size() != 0) {
			for (Enterprise enterprise : enterpriseList) {
				if (!CommonUtils.isBlank(enterprise.getEnterpriseGps())) {
					double lat2 = Double.valueOf(enterprise.getEnterpriseGps().split(",")[0]);
					double lng2 = Double.valueOf(enterprise.getEnterpriseGps().split(",")[1]);
					BigDecimal distanceE = new BigDecimal(CommonUtils.getDistance(lng1, lat1, lng2, lat2));
					LOG.debug("distance:" + distanceE);
					if (distance == null || distanceE.compareTo(distance) < 0) {
						distance = distanceE;
						position = i;
					}
				}
				i++;
			}
		}
		if (position != null) {
			enterpriseId = Integer.valueOf(enterpriseList.get(position).getId());
		}
		return enterpriseId;
	}

	/**
	 * 
	 * queryEnterpriseList:后台查询服务单位列表. <br/>
	 *
	 * @author puyf
	 * @param paramMap
	 * @return
	 * @throws Exception
	 * @since JDK 1.7
	 */
	public List<Enterprise> queryEnterpriseList(Map<String, Object> paramMap) throws Exception {
		// 获取服务单位列表
		List<Enterprise> enterpriseList = enterpriseDao.queryEnterpriseList(paramMap);
		return enterpriseList;
	}

	/**
	 * 
	 * queryEnterprise:查询服务单位实体. <br/>
	 *
	 * @author puyf
	 * @param id
	 * @return
	 * @throws Exception
	 * @since JDK 1.7
	 */
	public Map<String, Object> queryEnterprise(int id) throws Exception {
		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap.put("id", id);
		paramMap.put("objectType", BusinessConstant.FILE_TYPE_ENTERPRISE_IMG);
		// 获取服务单位实体
		Enterprise enterprise = enterpriseDao.queryEnterprise(paramMap);
		Map<String, Object> resultMap = new HashMap<String, Object>();
		// 返回对象
		if (enterprise != null) {
			// gps
			resultMap.put("enterpriseGps", enterprise.getEnterpriseGps());
			// 企业照片
			if (!CommonUtils.isBlank(enterprise.getEnterpriseImg())) {
				resultMap.put("enterpriseImg", adminUrl + enterprise.getEnterpriseImg());
			}
			// 企业名称
			resultMap.put("enterpriseName", enterprise.getEnterpriseName());
			// 企业地址
			resultMap.put("enterpriseAddress", enterprise.getEnterpriseAddress());
			// 企业联系人
			resultMap.put("enterpriseContact", enterprise.getEnterpriseContact());
			// 企业服务电话
			resultMap.put("enterpriseTel", enterprise.getEnterpriseTel());
			// 评分
			resultMap.put("enterpriseScore", enterprise.getEnterpriseScore());
			// 资质类别
			resultMap.put("enterpriseQualification", enterprise.getEnterpriseQualification());
			// 主营品牌
			resultMap.put("enterpriseBrand", enterprise.getEnterpriseBrand());
			// 认证
			resultMap.put("enterpriseCertification", enterprise.getEnterpriseCertification());
		}
		return resultMap;
	}

	/**
	 * 
	 * queryPeople:获取用户信息. <br/>
	 *
	 * @author puyf
	 * @param nickName
	 * @return
	 * @throws Exception
	 * @since JDK 1.7
	 */
	public WeixinPeopleEntity queryPeople(String nickName) throws Exception {
		Map<String, Object> requestMap = new HashMap<String, Object>();
		requestMap.put("nickName", nickName);
		WeixinPeopleEntity people = weixinPeopleDao.getWeixinPeopleEntity(requestMap);
		return people;
	}

	/**
	 * 
	 * modifyEnterpriseBind:绑定管理员帐号. <br/>
	 *
	 * @author puyf
	 * @param requestMap
	 * @return
	 * @throws Exception
	 * @since JDK 1.7
	 */
	public void modifyEnterpriseBind(Map<String, Object> requestMap) throws Exception {
		// 获取原该企业绑定的用户
		Map<String, Object> paramMap1 = new HashMap<String, Object>();
		paramMap1.put("enterpriseId", requestMap.get("enterpriseId"));
		WeixinPeopleEntity peopleOld = weixinPeopleDao.getWeixinPeopleEntity(paramMap1);
		if (peopleOld != null) {
			// 解除原用户绑定关系
			peopleOld.setPeopleRole(BusinessConstant.PEOPLE_ROLE_C);
			peopleOld.setPeopleEnterpriseId(null);
			peopleDao.updateEntity(peopleOld);
		}
		// 获取新用户信息
		Map<String, Object> paramMap2 = new HashMap<String, Object>();
		paramMap2.put("peopleId", requestMap.get("peopleId"));
		WeixinPeopleEntity peopleNew = weixinPeopleDao.getWeixinPeopleEntity(paramMap2);
		// 绑定新用户
		peopleNew.setPeopleRole(BusinessConstant.PEOPLE_ROLE_S);
		peopleNew.setPeopleEnterpriseId(Integer.valueOf((String) requestMap.get("enterpriseId")));
		peopleDao.updateEntity(peopleNew);

		// 销毁原用户新用户session
		Collection<Session> sessionList = sessionDao.getActiveSessions();
		if (peopleOld == null) {
			// 只找新用户
			Session peopleNewSession = null;
			for (Session session : sessionList) {
				if (session.getAttribute(SessionConstEnum.PEOPLE_SESSION.toString()) != null
						&& ((WeixinPeopleEntity) session.getAttribute(SessionConstEnum.PEOPLE_SESSION.toString()))
								.getPeopleId() == peopleNew.getPeopleId()) {
					peopleNewSession = session;
					break;
				}
			}
			// 销毁新用户session
			if (peopleNewSession != null) {
				try {
					// 单位毫秒
					peopleNewSession.setTimeout(0);
				} catch (InvalidSessionException e) {
				}
			}
		} else {
			// 新用户和原用户都要找
			Session peopleOldSession = null;
			Session peopleNewSession = null;
			for (Session session : sessionList) {
				if (session.getAttribute(SessionConstEnum.PEOPLE_SESSION.toString()) != null
						&& ((WeixinPeopleEntity) session.getAttribute(SessionConstEnum.PEOPLE_SESSION.toString()))
								.getPeopleId() == peopleOld.getPeopleId()) {
					peopleOldSession = session;
				}
				if (session.getAttribute(SessionConstEnum.PEOPLE_SESSION.toString()) != null
						&& ((WeixinPeopleEntity) session.getAttribute(SessionConstEnum.PEOPLE_SESSION.toString()))
								.getPeopleId() == peopleNew.getPeopleId()) {
					peopleNewSession = session;
				}
			}
			// 新用户和原用户都要销毁
			try {
				if (peopleOldSession != null) {
					peopleOldSession.setTimeout(0);
				}
				if (peopleNewSession != null) {
					peopleNewSession.setTimeout(0);
				}
			} catch (InvalidSessionException e) {
			}
		}
	}

	/**
	 * 
	 * translate:坐标转换. <br/>
	 *
	 * @author puyf
	 * @param locations
	 * @return
	 * @since JDK 1.7
	 */
	private String translateGps(String locations) {
		String url = BusinessConstant.TRANSLATE_URL + "locations=" + locations + "&type=3&key="
				+ BusinessConstant.MAP_KEY;
		HttpGet get = HttpClientConnectionManager.getGetMethod(url);
		DefaultHttpClient HTTPCLIENT = new DefaultHttpClient();
		String baiduLocation = null;
		try {
			HttpResponse responses = (HttpResponse) HTTPCLIENT.execute(get);
			String jsonStr = EntityUtils.toString(responses.getEntity(), "utf-8");
			LOG.debug(jsonStr);
			if ((Integer) ((JSONObject) JSONObject.parse(jsonStr)).get("status") == 0) {
				// 返回成功
				JSONArray elements = (JSONArray) ((JSONObject) JSONObject.parse(jsonStr)).get("locations");
				Iterator<Object> it = elements.iterator();
				while (it.hasNext()) {
					JSONObject location = (JSONObject) it.next();
					baiduLocation = location.get("lat") + "," + location.get("lng");
				}
			}
		} catch (Exception e) {
			LOG.error("转换坐标失败", e);
		}
		return baiduLocation;
	}

	/**
	 * 
	 * getNearestGps:获取最近gps. <br/>
	 *
	 * @author puyf
	 * @param from
	 * @param to
	 * @return
	 * @since JDK 1.7
	 */
	private Integer getNearestGps(String from, String to) {
		Integer position = null;
		String url = BusinessConstant.DISTANCE_URL_BD + "output=json&coord_type=bd09ll&origins=" + from
				+ "&destinations=" + to + "&ak=" + BusinessConstant.MAP_KEY_BD;
		HttpGet get = HttpClientConnectionManager.getGetMethod(url);
		DefaultHttpClient HTTPCLIENT = new DefaultHttpClient();
		try {
			HttpResponse responses = (HttpResponse) HTTPCLIENT.execute(get);
			String jsonStr = EntityUtils.toString(responses.getEntity(), "utf-8");
			LOG.debug(jsonStr);
			if ((Integer) ((JSONObject) JSONObject.parse(jsonStr)).get("status") == 0) {
				// 返回成功
				Integer distance = null;

				JSONArray elements = (JSONArray) ((JSONObject) JSONObject.parse(jsonStr)).get("result");
				Iterator<Object> it = elements.iterator();
				int i = 0;
				while (it.hasNext()) {
					JSONObject location = (JSONObject) it.next();
					Integer distanceE = (Integer) ((JSONObject) location.get("distance")).get("value");
					if (distance == null || distanceE < distance) {
						distance = distanceE;
						position = i;
					}
					i++;
				}
			}
		} catch (Exception e) {
			LOG.error("获取最近服务单位失败", e);
		}
		return position;
	}
}
